﻿#include "protocolconvert.h"
#include <QDebug>
#include "../commons/configfile.h"
#include "../logs/printlogs.h"


ProtocolConvert * ProtocolConvert::m_protocolConvert = NULL;
ProtocolConvert::ProtocolConvert(QObject *parent) : QObject(parent)
  , m_serial(NULL)
  , m_packageNumbers(0)
{
    m_comAlgor = new ComAlgor();
    m_serial = new QSerialPort();
    connect(m_serial,SIGNAL( readyRead() ),this,SLOT( onDataReceived() ));
    initComSeriel();
}

ProtocolConvert::~ProtocolConvert()
{

}

ProtocolConvert *ProtocolConvert::gestance()
{
    if(m_protocolConvert == NULL){
        m_protocolConvert = new ProtocolConvert();
    }

    return m_protocolConvert;
}

void ProtocolConvert::initComSeriel()
{
    QString names =  ConfigFile::gestance()->getCom1Name();
#ifdef DEBUG_INFOR
    qDebug()<< metaObject()->className()<<"names=="<<names;
#endif
    if(names.length() > 0){
#ifdef DEBUG_INFOR
        qDebug()<< metaObject()->className()<<__func__<<__LINE__;
#endif
        QSerialPortInfo info(names);
        m_serial->setPortName(names);
        qDebug()<<__func__<<__LINE__<<"PortName=="<<names;
        m_serial->setBaudRate(QSerialPort::Baud115200);
        m_serial->setParity(QSerialPort::NoParity);
        m_serial->setDataBits(QSerialPort::Data8);
        m_serial->setStopBits(QSerialPort::OneStop);
        m_serial->setFlowControl(QSerialPort::NoFlowControl);

        if(m_serial->open(QIODevice::ReadWrite)) // 以读写方式打开串口
        {
#ifdef DEBUG_INFOR
            qDebug()<< metaObject()->className()<<__func__<<__LINE__;
#endif
        }
#ifdef DEBUG_INFOR
        qDebug()<< metaObject()->className()<<__func__<<__LINE__;
#endif
    }
}

void ProtocolConvert::retCmdInfor(QByteArray infors)
{
    uint16_t check_crc=0;
    int lenas=infors.size();
    uint8_t enda[6];
    uint8_t cmda[30];
    cmda[0]= (uint8_t)0x4C;
    cmda[1]= (uint8_t)m_packageNumbers;
    cmda[2]= (uint8_t)(m_packageNumbers >> 8);
    cmda[3]= (uint8_t)0x01;
    cmda[4]= (uint8_t)0x80;
    cmda[5]= m_retCmd;
    cmda[6]= (uint8_t)lenas;
    cmda[7]= (uint8_t)(lenas >> 8);
    QByteArray sends((char * )cmda,8);
    sends.append(infors);
    check_crc=m_comAlgor->CRC16((unsigned char *)sends.data() +1,sends.size() -1);
    enda[0]= (uint8_t)check_crc;
    enda[1]= (uint8_t)(check_crc >> 8);
    enda[2]= (uint8_t)0x49;
    QByteArray send2((char * )enda,3);
    sends.append(send2);
#ifdef DEBUG_INFOR
    qDebug()<< metaObject()->className()<<__func__<<__LINE__<<sends.toHex();
#endif
    if(m_serial != NULL){
        m_serial->write(sends);
        m_serial->flush();
    }
    // m_packageNumbers++;
}

void ProtocolConvert::findLevel(QMap<int, int> maps)
{
    m_retCmd = (uint8_t)0x8E;
    QByteArray infors;
    char typs = 0x00;
    QByteArray infora((char *)&typs,1);
    QList<int> lista = maps.keys();
#ifdef DEBUG_INFOR
    qDebug()<< metaObject()->className()<<__func__<<__LINE__<<lista;
#endif
    typs =(char) lista.size();
    QByteArray inforb((char *)&typs,1);
    infors.append(infora);
    infors.append(inforb);
    for(int i = 0 ;i < lista.size() ;i++){
        int pins =  lista.at(i);
        int valuse = maps.value(pins);
#ifdef DEBUG_INFOR
        qDebug()<< metaObject()->className()<<__func__<<__LINE__<<pins;
        qDebug()<< metaObject()->className()<<__func__<<__LINE__<<valuse;
#endif
        uint8_t conta[6];
        conta[0] = (uint8_t)(valuse );
        conta[1] = (uint8_t)(valuse >> 8);
        conta[2] = (uint8_t)(valuse >> 16);
        conta[3] = (uint8_t)(valuse >> 24);
        QByteArray infora((char *)conta,4);
        infors.append(infora);
    }
    retCmdInfor(infors);
}

void ProtocolConvert::lackMaterials(uint8_t cmda,uint8_t typs)
{
    m_retCmd =cmda;

    QByteArray infors((char *)&typs,1);
    retCmdInfor(infors);
}

void ProtocolConvert::cleanCmdEnd(uint8_t cmda,int errors)
{
    m_retCmd =cmda;
    QByteArray infors((char*)&errors,1);
    retCmdInfor(infors);
}

void ProtocolConvert::handlMixDeviceSuccess()
{
    m_retCmd =0x7A;
    char errors = 0;
    QByteArray infors((char*)&errors,1);
    retCmdInfor(infors);
}

void ProtocolConvert::handlNotsupported(uint8_t cmda, uint8_t typs,uint8_t error)
{
    m_retCmd =cmda;
    //  QByteArray infors((char*)&typs,1);
    char cha=error;
    QByteArray ba = QByteArray(&cha,1);

    QByteArray infors = ba;//+infors;
    if(error !=   0x04 ){
        QByteArray inforas((char*)&typs,1);
        infors = infors+inforas;
    }
    retCmdInfor(infors);
}

void ProtocolConvert::handlDevices(uchar cmds, QByteArray infors)
{
    m_retCmd =cmds;
    QByteArray infora =infors;
    retCmdInfor(infora);
}

void ProtocolConvert::closeComSeriel()
{
    if(m_serial != NULL){
        m_serial->close();
    }
#ifdef DEBUG_INFOR
    qDebug()<< metaObject()->className()<<__func__<<__LINE__<<"names=="<<m_serial->error();

#endif
}

void ProtocolConvert::openComSeriel()
{
    if(m_serial != NULL){
        if(m_serial->open(QIODevice::ReadWrite)) // 以读写方式打开串口
        {
#ifdef DEBUG_INFOR
            qDebug()<< metaObject()->className()<<__func__<<__LINE__;
#endif

        }
    }
}

void ProtocolConvert::onDataReceived()
{
    if(m_serial != NULL){

        uint8_t cha[2];
        cha[0]=0x4C;
        cha[1]='X';

        QByteArray data = m_serial->readAll();
        m_currentData.append(data);
        //   #ifdef DEBUG_INFOR   qDebug()<< metaObject()->className()<<__func__<<__LINE__<<"data=="<<data.toHex();

        bool isEnd = false;
        uint16_t temp_check1 = 0;
        uint16_t temp_check2 = 0;
        uint16_t packages = 0;
        uint8_t ends = 0;
        uint8_t cmds = 0;
        uint16_t uart_lens = 0;
        QByteArray currentData;

        for (int i = 0; i < m_currentData.size(); i++) {
#ifdef DEBUG_INFOR
            qDebug()<< metaObject()->className()<<__func__<<__LINE__<<"i=="<<i;
#endif
            if ((uchar)m_currentData[i] == (uchar)0x4C && 11 <=  m_currentData.size() ) {
#ifdef DEBUG_INFOR
                qDebug()<< metaObject()->className()<<__func__<<__LINE__<<"m_currentData=="<<m_currentData.toHex();
#endif
                packages = (uchar)m_currentData[i+2];
                packages = (packages << 8);
                packages += (uchar)m_currentData[i+1];
                m_packageNumbers = packages;
#ifdef DEBUG_INFOR
                qDebug()<< metaObject()->className()<<__func__<<__LINE__<<"packages=="<<packages;
#endif
                cmds = (uchar)m_currentData[i+5];
#ifdef DEBUG_INFOR
                qDebug()<< metaObject()->className()<<__func__<<__LINE__<<"cmds=="<<cmds;
#endif
                uart_lens= (uchar)m_currentData[i+7];
                uart_lens = (uart_lens << 8);
                uart_lens += (uchar)m_currentData[i+6];
#ifdef DEBUG_INFOR
                qDebug()<< metaObject()->className()<<__func__<<__LINE__<<"uart_lens=="<<uart_lens;
#endif
                temp_check1 = (uchar)m_currentData[i+9+uart_lens];
                temp_check1 = (temp_check1 << 8);
                temp_check1 +=(uchar) m_currentData[i+8+uart_lens];
#ifdef DEBUG_INFOR
                qDebug()<< metaObject()->className()<<__func__<<__LINE__<<"temp_check1=="<<temp_check1;
#endif
                ends =(uchar) m_currentData[i+10+uart_lens];
#ifdef DEBUG_INFOR
                qDebug()<< metaObject()->className()<<__func__<<__LINE__<<"ends=="<<ends;
#endif
#ifdef DEBUG_LOG_INFOR
                QString printlogStr=typeid(this).name()+QString(" %1").arg( __func__) +" -- "+ QString("%1").arg( __LINE__)  + QString(" = ") + m_currentData.toHex();
                PrintLogb::gestance()->printInfor(printlogStr);
#endif
                if(ends == 0x49){
                    temp_check2=m_comAlgor->CRC16((unsigned char *)(m_currentData.data()+i + 1),uart_lens +8 -1);
#ifdef DEBUG_INFOR
                    qDebug()<< metaObject()->className()<<__func__<<__LINE__<<"temp_check2=="<<temp_check2;
#endif
                    if(temp_check2 == temp_check1){
                        currentData = QByteArray(m_currentData.data()+i+8,uart_lens);
#ifdef DEBUG_INFOR
                        qDebug()<< metaObject()->className()<<__func__<<__LINE__<<"currentData=="<<currentData.toHex();
#endif

                        isEnd = true;
                    }else{
#ifdef DEBUG_INFOR
                        qDebug()<< metaObject()->className()<<__func__<<__LINE__;
#endif
                        lackMaterials(cmds,0x01);
                    }

                    m_currentData.clear();
                    break;
                }

            }
        }


        if(isEnd){
#ifdef DEBUG_INFOR
            qDebug()<< metaObject()->className()<<__func__<<__LINE__<<"cmds=="<<cmds;

#endif
#ifdef DEBUG_LOG_INFOR
            QString printlogStr=typeid(this).name()+QString(" %1").arg( __func__) +" -- "+ QString("%1").arg( __LINE__)  + QString(" = ") + QString("%1").arg( cmds);
            PrintLogb::gestance()->printInfor(printlogStr);
#endif
            if(cmds == (uint8_t) 0x8E){

                emit sigFindLevel();
            }
            if(cmds == (uint8_t) 0x22  ){

                emit sigSequentialDischarge(cmds ,currentData);
            }
            if(cmds == (uint8_t) 0x23  || cmds == (uint8_t) 0x21){

                emit sigSameDischarge(cmds,currentData);
            }
            if( cmds == (uint8_t) 0x24 || cmds == (uint8_t) 0x27 || cmds == (uint8_t) 0x26 || cmds == (uint8_t) 0x25 ){

                lackMaterials(cmds,0x86);
            }
            //不支持指令
            if(cmds == (uint8_t) 0x04 || cmds == (uint8_t) 0x2B  || cmds == (uint8_t) 0x2E || cmds == (uint8_t) 0x43 || cmds == (uint8_t) 0x44 || cmds == (uint8_t) 0x45     || cmds == (uint8_t) 0x5B || cmds == (uint8_t) 0x5C  || cmds == (uint8_t) 0x5E || cmds == (uint8_t) 0x6A || cmds == (uint8_t) 0x6B   || cmds == (uint8_t) 0x7A || cmds == (uint8_t) 0x7B || cmds == (uint8_t) 0x7C || cmds == (uint8_t) 0x7D || cmds == (uint8_t) 0x89 || cmds == (uint8_t) 0x8A ||cmds == (uint8_t) 0x89 ||cmds == (uint8_t) 0x8A || cmds == (uint8_t) 0x8C || cmds == (uint8_t) 0x8D || cmds == (uint8_t) 0x94 || cmds == (uint8_t) 0x95){

                emit  sigNotsupported(  cmds,  currentData);

            }
            //清洗
            if(cmds == (uint8_t) 0x42||cmds == (uint8_t) 0x46){
                int indexs = 0;
                if(currentData.length() >= 1){
                    indexs = (uchar) currentData.at(0);
                }
#ifdef DEBUG_INFOR
                qDebug()<< metaObject()->className()<<__func__<<__LINE__<<"indexs=="<<indexs;
#endif
                emit sigCleanIndex(cmds, indexs);
            }

            //搅拌机
            if(cmds == (uint8_t) 0x83||cmds == (uint8_t) 0x88  || cmds == (uint8_t) 0x2C){

                emit sigSolenoidValve(cmds,currentData);
            }
            if(cmds == (uint8_t) 0xA4 || cmds == (uint8_t) 0x01 || cmds == (uint8_t) 0x02|| cmds == (uint8_t) 0x03|| cmds == (uint8_t) 0x11 || cmds == (uint8_t) 0x12  || cmds == (uint8_t) 0x86 || cmds == (uint8_t) 0xC1  || cmds == (uint8_t) 0xC3  || cmds == (uint8_t) 0xC5  || cmds == (uint8_t) 0xC7  || cmds == (uint8_t) 0x53 || cmds == (uint8_t) 0x5D || cmds == (uint8_t) 0x6C || cmds == (uint8_t)0xA3 || cmds == (uint8_t)0xA0 || cmds == (uint8_t)0xA2 || cmds == (uint8_t) 0x54 ){

                emit sigDevices(  cmds);
            }
            //查询指令
            if(cmds == (uint8_t) 0x10 || cmds == (uint8_t) 0x2A || cmds == (uint8_t) 0x41 || cmds == (uint8_t) 0x47  || cmds == (uint8_t) 0x84 || cmds == (uint8_t) 0x85 || cmds == (uint8_t) 0x87  || cmds == (uint8_t) 0x9A  || cmds == (uint8_t) 0xB0 || cmds == (uint8_t) 0xB1  || cmds == (uint8_t) 0xC0 || cmds == (uint8_t) 0xC2  || cmds == (uint8_t) 0xC4  || cmds == (uint8_t) 0xC6 || cmds == (uint8_t) 0xC8 || cmds == (uint8_t) 0x2D){

                emit sigFindRuns(  cmds);
            }
            if(cmds == (uint8_t) 0x28 || cmds == (uint8_t) 0x29 || cmds == (uint8_t) 0x48 || cmds == (uint8_t) 0x51  || cmds == (uint8_t) 0x52 ){

                emit sigCloseValues(  cmds, currentData);

            }
        }
    }

}
